<template>
    <xcmg-drawer v-model="_visible" :title="title" size="small" hideFooter>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm"
            :size="formSize" status-icon>
            <el-form-item label="问题示例" prop="ruleCode">
                <xcmg-input v-model="ruleForm.ruleCode" :rows="rows" type="textarea" placeholder="请输入问题示例，不同问题用回车隔开" />
            </el-form-item>
            <el-form-item label="答案示例" prop="description">
                <xcmg-input v-model="ruleForm.description" placeholder="请输入答案示例" />
            </el-form-item>
            <el-form-item label="参考图片" prop="images">
                <el-upload v-model:file-list="imageList"
                    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" list-type="picture-card"
                    :on-preview="handlePictureCardPreview" :auto-upload="false" :before-upload="beforeImageUpload"
                    accept="image/*" multiple drag>

                    <div class="el-upload__text">
                        将图片拖到此处，或 <em>点击上传</em>
                    </div>
                </el-upload>
                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </el-form-item>
            <el-form-item label="参考文件" prop="files">
                <el-upload class="upload-demo" drag multiple v-model:file-list="fileList"
                    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" :auto-upload="false"
                    :before-upload="beforeFileUpload">
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                        将文件拖到此处，或 <em>点击上传</em>
                    </div>
                </el-upload>
            </el-form-item>
            <el-form-item label="处理方式" prop="active">
                <xcmg-input v-model="ruleForm.active" placeholder="请输入处理方式" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="drawer-footer">
                <el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
                <el-button @click="handleSaveClose(ruleFormRef)">关闭</el-button>
            </div>
        </template>
    </xcmg-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import type { FormInstance, UploadUserFile } from 'element-plus'
import { UploadFilled, Plus } from '@element-plus/icons-vue'
import { XcmgMessage } from 'xcmg-components'

const props = defineProps<{
    title: string;
    visible: boolean,
}>();

const emit = defineEmits(['update:visible', 'queryMaterialRule']);

const _visible = computed({
    get() {
        return props.visible;
    },
    set(val) {
        emit('update:visible', val);
    },
});

interface RuleForm {
    ruleCode: string
    description: string
    active: string
}

const formSize = ref('default')
const rows = ref(3)
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    ruleCode: '',
    description: '',
    active: ''
})

const rules = reactive({
    ruleCode: [
        { required: true, message: '请输入问题示例', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入答案示例', trigger: 'blur' }
    ],
    active: [
        { required: true, message: '请输入处理方式', trigger: 'blur' }
    ]
})

// 图片上传相关
const imageList = ref<UploadUserFile[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const beforeImageUpload = (file: File) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        XcmgMessage.error('只能上传图片文件!')
        return false
    }
    if (!isLt2M) {
        XcmgMessage.error('图片大小不能超过 2MB!')
        return false
    }
    return true
}

const handlePictureCardPreview = (file: UploadUserFile) => {
    dialogImageUrl.value = file.url!
    dialogVisible.value = true
}

// 文件上传相关
const fileList = ref<UploadUserFile[]>([])

const beforeFileUpload = (file: File) => {
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
        XcmgMessage.error('文件大小不能超过 10MB!')
        return false
    }
    return true
}

// 上传函数
const uploadFiles = async (files: UploadUserFile[]) => {
    const formData = new FormData()

    // 添加文件到FormData
    files.forEach(file => {
        // 如果是已经上传过的文件（有response），可以跳过或处理
        if (file.raw) {
            formData.append('files', file.raw)
        }
    })

    try {
        // 替换为实际的上传API
        const response = await fetch('https://your-real-api-endpoint.com/upload', {
            method: 'POST',
            body: formData
        })

        if (!response.ok) {
            throw new Error('上传失败')
        }

        return await response.json()
    } catch (error) {
        console.error('上传失败:', error)
        throw error
    }
}

const handleSave = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    try {
        // 验证表单
        await formEl.validate()

        // 准备上传所有图片和文件
        const allFiles = [...imageList.value, ...fileList.value]
            .filter(file => file.raw) // 只选择未上传的文件

        if (allFiles.length > 0) {
            // 上传文件
            const uploadResult = await uploadFiles(allFiles)
            console.log('上传结果:', uploadResult)
        }

        // 准备提交的数据
        const submitData = {
            ...ruleForm,
            images: imageList.value.map(img => ({
                name: img.name,
                url: img.url || img.response?.url // 已上传的URL或新上传的URL
            })),
            files: fileList.value.map(file => ({
                name: file.name,
                url: file.url || file.response?.url
            }))
        }

        // 这里可以添加提交表单数据的逻辑
        console.log('提交数据:', submitData)

        XcmgMessage.success('保存成功')
    } catch (error) {
        console.error('保存失败:', error)
        XcmgMessage.error('保存失败，请检查表单')
    }
}

const handleSaveClose = async (formEl: FormInstance | undefined) => {
    await handleSave(formEl)
    _visible.value = false
}
</script>

<style scoped>
:deep(.el-form-item__content) {
    display: flex;
}

:deep(.drawer-content) {
    padding-bottom: 0px !important;
}

.drawer-footer {
    border-top: none !important;
}
</style>